# -*- encoding: utf-8 -*-
'''
@File    :   index.py
@Time    :   2020年12月20日 10:47:03 星期天
@Author  :   ermao
@Version :   1.0
@Link    :   https://erma0.cn
@Desc    :   Vercel托管API
'''

print('start index.py')

# 导入需求模块
# import json
import requests
from flask import Flask, request, jsonify

# 导入lib目录中的功能模块，随用随导入，没有用到的不会占用内存

# 需要设置返回header时
# from flask import make_response
# 需要用内置库将URL参数字符串解析成字典时
# from urllib.parse import parse_qs

# 云端库无法引入目录，先设置环境变量
import sys
sys.path.append('api/lib')
sys.path.append('api')
sys.path.append('.')

app = Flask(__name__)

# 根目录下配置vercel.json，路由信息
'''
{
    "routes": [{
        "src": "/api/(.*)",
        "dest": "api/index.py"
    }]
}
'''

# jsonify返回中文直接显示，不加这一句的话会编码Unicode
app.config['JSON_AS_ASCII'] = False

# 返回jsonp解决跨域
# def jsonp(resp):
#     callback = request.args.get('callback')
#     return '{}({})'.format(callback, json.dumps(resp))


# 设置允许跨域
@app.after_request
def cors(environ):
    environ.headers['Access-Control-Allow-Origin'] = '*'
    environ.headers['Access-Control-Allow-Method'] = '*'
    environ.headers[
        'Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return environ


# 设置404返回模板
@app.errorhandler(404)
def not_found(error):
    resp = {'作者': '二毛', 'QQ': '1737882100', '主页': 'https://erma0.cn'}
    return jsonify(resp), 404


# 无参数
@app.route('/api', methods=['GET', 'POST'])
def index():
    resp = {'作者': '二毛', 'QQ': '1737882100', '主页': 'https://erma0.cn'}
    return jsonify(resp)


# @NAME :   IP定位
# @URL  :   /ip?ip=123.123.123.123
# @URL  :   /ip?longitude=123.26011&latitude=34.176219
@app.route('/api/ip', methods=['GET'])
def get_ip_info():
    from lib import ip as iplib
    user_ip = request.remote_addr
    ip = request.args.get('ip', user_ip)
    latitude = request.args.get('latitude')
    longitude = request.args.get('longitude')
    if longitude:
        resp = iplib.location_info(longitude, latitude)
    elif ip:
        resp = iplib.locate(ip)
    else:
        resp = {'error': '参数错误！'}
    resp['ip'] = ip
    return jsonify(resp)


# @NAME :   QQ信息（昵称、头像）查询
# @URL  :   /qq?num=1737882100
@app.route('/api/qq', methods=['GET'])
def qq_info():
    from lib import qq
    num = request.args.get('num')
    if num:
        resp = qq.get_info(num)
    else:
        resp = {'msg': 'QQ号格式错误！'}
    return jsonify(resp)


# @NAME :   短信炸弹
# @URL  :   /sms?phone=15221395158
@app.route('/api/sms', methods=['GET'])
def sms():
    from lib import sms_boom
    phone = request.args.get('phone')
    if phone:
        sms_boom.send_sms(phone)
        resp = {'msg': '已提交！'}
    else:
        resp = {'msg': '手机号错误！'}
    return jsonify(resp)


# @NAME :   抖音查询用户/作品
# @URL  :   /douyin?type=user&id=tuantuanxhchibb
# @URL  :   /douyin?type=user&url=https://v.douyin.com/JBknYQp/
# @URL  :   /douyin?type=video&id=6808453751930719502
# @URL  :   /douyin?type=video&url=https://v.douyin.com/JBBebxv/
@app.route('/api/douyin', methods=['GET'])
def douyin_parse():
    from lib import douyin
    try:
        query = request.args.to_dict()
        _type = query.pop('type', None)  # user/video
        key = list(query.keys())[0]  # id/url
        value = query[key]
        f = 'douyin.parse_{}_by_{}("{}")'.format(_type, key, value)
        # print(f)
        resp = eval(f)
    except Exception as e:
        resp = {'error': str(e)}
    return jsonify(resp)


# @NAME :   快手查询用户/作品
# @URL  :   /kuaishou?type=user&id=sanda927
# @URL  :   /kuaishou?type=user&url=https://v.kuaishou.com/6vPcKW
# @URL  :   /kuaishou?type=video&id=3xrkjbikwdh5chm
# @URL  :   /kuaishou?type=video&url=https://v.kuaishou.com/4WAqVg
@app.route('/api/kuaishou', methods=['GET'])
def kuaishou_parse():
    from lib import kuaishou
    try:
        query = request.args.to_dict()
        _type = query.pop('type', None)  # user/video
        key = list(query.keys())[0]  # id/url
        value = query[key]
        f = 'kuaishou.parse_{}_by_{}("{}")'.format(_type, key, value)
        # print(f)
        resp = eval(f)
    except Exception as e:
        resp = {'error': str(e)}
    return jsonify(resp)


# @NAME :   各种网盘查提取码
# @URL  :   /api/pan?url=https://pan.baidu.com/s/1Qg4VrIu3KwmKWa_DwacWcA
@app.route('/api/pan', methods=['GET'])
def pan_parsing():
    from lib import pan
    url = request.args.get('url')
    if url:
        resp = pan.get_pan(url)
    else:
        resp = {'error': '参数错误！'}
    return jsonify(resp)


# @NAME :   小米运动刷步数
# @URL  :   /api/walk?user=18888888&pass=666666[&step=12222]
@app.route('/api/walk', methods=['GET'])
def walk():
    from lib import walk
    user = request.args.get('user')
    pwd = request.args.get('pass')
    step = request.args.get('step')
    if user and pwd:
        resp = walk.main(user, pwd, step)
    else:
        resp = {'error': '请输入正确的用户名和密码！'}
    return jsonify(resp)


# # 阿里云函数计算云端入口
# def handler(environ, start_response):
#     return app(environ, start_response)

# 本地调试
if __name__ == "__main__":
    app.run(host='0.0.0.0', port=2222)

# # @NAME :   抖音查询用户信息
# # @URL  :   /douyin/user?uid=72673737181
# # @URL  :   /douyin/user?url=https://v.douyin.com/JBknYQp/
# @app.route('/api/douyin/user', methods=['GET'])
# def douyin_userinfo():
#     from lib import douyin
#     uid = request.args.get('uid')
#     url = request.args.get('url')
#     if uid:
#         resp = douyin.user_info(uid)
#     elif url:
#         resp = douyin.user_info_url(url)
#     else:
#         resp = {'error': '参数错误！'}
#     return jsonify(resp)

# # @NAME :   抖音解析去水印视频
# # @URL  :   /douyin/parse?id=6808453751930719502
# # @URL  :   /douyin/parse?url=https://v.douyin.com/JBBebxv/
# @app.route('/api/douyin/parse', methods=['GET'])
# def douyin_parsing():
#     from lib import douyin
#     id = request.args.get('id')
#     url = request.args.get('url')
#     if id:
#         resp = douyin.parse_by_id(id)
#     elif url:
#         resp = douyin.parse_by_url(url)
#     else:
#         resp = {'error': '参数错误！'}
#     return jsonify(resp)
#    # return jsonp(resp)

# # @NAME :   快手查询用户信息
# # @URL  :   /kuaishou/user?id=sanda927
# # @URL  :   /kuaishou/user?url=https://v.kuaishou.com/6vPcKW
# @app.route('/api/kuaishou/user', methods=['GET'])
# def kuaishou_userinfo():
#     from lib import kuaishou
#     id = request.args.get('id')
#     url = request.args.get('url')
#     if id:
#         resp = kuaishou.user_info(id)
#     elif url:
#         resp = kuaishou.user_info_url(url)
#     else:
#         resp = {'error': '参数错误！'}
#     return jsonify(resp)

# # @NAME :   快手解析去水印视频
# # @URL  :   /kuaishou/parse?id=3xrkjbikwdh5chm
# # @URL  :   /kuaishou/parse?url=https://v.kuaishou.com/4WAqVg
# @app.route('/api/kuaishou/parse', methods=['GET'])
# def kuaishou_parsing():
#     from lib import kuaishou
#     id = request.args.get('id')
#     url = request.args.get('url')
#     if id:
#         resp = kuaishou.parse_by_id(id)
#     elif url:
#         # resp = kuaishou.parse_by_url2(url)
#         resp = kuaishou.parse_by_url(url)
#     else:
#         resp = {'error': '参数错误！'}
#     return jsonify(resp)
#     # return jsonp(resp)

# # @NAME :   快手刷新cookie的did
# # @URL  :   /kuaishou/did
# @app.route('/api/kuaishou/did', methods=['GET'])
# def did():
#     from lib import kuaishou
#     resp = kuaishou.refresh_did()
#     return jsonify(resp)
